"use strict";

const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");

// 获取npm的信息
function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null;
  }
  const registryUrl = registry || getDefaultRegistry(); // 处理registry地址
  const npmInfoUrl = urlJoin(registryUrl, npmName); // 拼接包地址
  // 请求包地址 获取版本列表
  return axios
    .get(npmInfoUrl)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      }
      return null;
    })
    .catch((err) => {
      return Promise.reject(err);
    });
}
// 处理默认registry
function getDefaultRegistry(isOriginal = false) {
  return isOriginal
    ? "https://registry.npmjs.org"
    : "https://registry.npm.taobao.org";
}
// 获取所有versions
async function getNpmVersions(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}
// 获取所有大于等于当前版本的版本号
function getSemverVersions(currentVersion, versions) {
  return versions
    .filter((version) => {
      // 大于等于当前版本号
      semver.satisfies(version, `^${currentVersion}`);
    })
    .sort((a, b) => {
      // 进行排序 防止返回的版本号不是由大到小
      return semver.gt(b, a);
    });
}
// 获取最新的版本号
async function getNpmSemverVersions(currentVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  const newVersions = getSemverVersions(currentVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }
  return null;
}

module.exports = {
  getNpmVersions,
  getNpmInfo,
  getNpmSemverVersions,
};
